import React from 'react'
import Taro from '@tarojs/taro'
import './index.less'
import http from '../../utils/http'

import { View, Text } from "@tarojs/components";
import { AtForm, AtInput, AtButton, AtMessage } from 'taro-ui'



class Login extends React.Component {
  constructor() {
    super(...arguments)
    this.state = {
      phone: '',
      password: ''
    }
  }
  phoneChange = (phone) => {
    this.setState({ phone })
  }
  passwordChange = (password) => {
    this.setState({ password })
  }
  onSubmit = async () => {
    const { data: res } = await http({
      url: '/login/land',
      method: 'post',
      data: this.state
    })
    if (res.error !== 0) {
      Taro.atMessage({
        'message': '登陆失败',
        'type': 'error',
      })
    } else {
      const userInfo = JSON.stringify(res.data)
      /* 存储用户信息 */
      Taro.setStorageSync('userInfo', userInfo)
      /* 存储token */
      Taro.setStorageSync('token', res.data.token)
      Taro.switchTab({
        url: '/pages/home/index'
      })
    }
  }

  componentDidMount() {
    const token = Taro.getStorageSync('token')
    if (token) {
      Taro.switchTab({
        url: '/pages/home/index'
      })
    }
  }
  render() {
    return (
      <View className='login_box'>
        <AtMessage />
        <View>
          {/* logo */}
          <View className='h1'>
            <Text>E-learning平台</Text>
          </View>

          {/* 登陆表单 */}
          <AtForm
            className='login_form'
            onSubmit={this.onSubmit}
          >
            <AtInput
              name='phone'
              type='number'
              className='phoneInp'
              placeholder='请输入手机号'
              border={false}
              value={this.state.phone}
              onChange={this.phoneChange}
            />
            <AtInput
              name='password'
              type='password'
              className='passwordInp'
              placeholder='请输入密码'
              border={false}
              value={this.state.password}
              onChange={this.passwordChange}
            />
            <AtButton className='submitBtn' type='primary' formType='submit'>提交</AtButton>
          </AtForm>
        </View>
      </View>
    )
  }
}

export default Login